<?php
error_reporting(E_ALL ^ E_NOTICE); // Report all errors except E_NOTICE warnings
//error_reporting(E_ALL); // Report all errors and warnings (very strict, use for testing only)
ini_set('display_errors', 1); // turn error reporting on
//ini_set('log_errors', 1); // log errors
//ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); // where to log errors
/*
IP To Country PHP Script by Mike Challis
Free PHP Scripts - www.642weather.com/weather/scripts.php
Download         - www.642weather.com/weather/scripts/ip-to-country.zip
Live Demo        - www.642weather.com/weather/ip-to-country.php
Contact Mike     - www.642weather.com/weather/contact_us.php

Version: 1.50 - 06-Dec-2008 see changelog.txt for changes

You are free to use and modify the code

This php code provided "as is", and Long Beach Weather (Michael Challis)
disclaims any and all warranties, whether express or implied, including
(without limitation) any implied warranties of merchantability or
fitness for a particular purpose.

Copyright (C) 2008 Mike Challis  (www.642weather.com/weather/contact_us.php)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

// include settings file
require 'ip-to-country-config.php';

// backwards compatibility with version 1.00
if (isset($non_buffer) && $non_buffer == 1) {
    $C['non_buffer'] = 1;
}

if ($C['non_buffer'] && ob_get_level() == 0) {
    ob_start();
}

 echo "Preparing to update ip-to-country database...<br />";
    if ($C['non_buffer']) {
         non_buffer();
    }

 if (!is_file( 'ip-to-country.csv' )) {
     echo '<p>Error: Cannot find the ip-to-country.csv data file,
	 it must be uploaded to the same directory as this script.</p>
     <p>You can download the latest data file here:
     <a href="http://ip-to-country.webhosting.info/node/view/6">http://ip-to-country.webhosting.info/node/view/6</a></p>';
     exit;
 }

 if ( $C['dbpass'] == '' || $C['dbuser'] =='' || $C['dbname'] == '' ) {
     echo '<p>Error: You need to set the settings for dbname, dbuser, and dbpass for this script to function.</p>';
     exit;
 }


 echo "Connecting to database...<br />";
    if ($C['non_buffer']) {
         non_buffer();
    }

    // Connect to mysql database
	$dbh = mysql_connect($C['dbhost'], $C['dbuser'], $C['dbpass']);
    if (!$dbh) die('Could not connect: ' . mysql_error());
    mysql_select_db($C['dbname']) or die(mysql_error());
 echo "Connected to database...<br />";
    if ($C['non_buffer']) {
         non_buffer();
    }

    // see if the country_info table already exists
    $result = mysql_query("show tables like 'country_info'",$dbh);
    if ( mysql_num_rows($result) > 0 ) {

      echo "Emptying the table first ...<br />";
      if ($C['non_buffer']) {
         non_buffer();
      }

      // empty the table first
      $query = "TRUNCATE TABLE country_info";
	  $result = mysql_query($query) or die("Invalid query: " . mysql_error().__LINE__.__FILE__);

    } else {

      echo "Creating country_info table now...<br />";
      if ($C['non_buffer']) {
         non_buffer();
      }

      // create the table now
      $table = "CREATE TABLE country_info (
                IP_FROM double NOT NULL default '0',
                IP_TO double NOT NULL default '0',
                COUNTRY_CODE2 char(2) NOT NULL default '',
                COUNTRY_CODE3 char(3) NOT NULL default '',
                COUNTRY_NAME varchar(50) NOT NULL default ''
                ) TYPE=MyISAM;";
       $result = mysql_query($table) or die("Invalid query: " . mysql_error().__LINE__.__FILE__);
    }

 echo "Please allow (10-30 seconds) for the data to load...<br />";
    if ($C['non_buffer']) {
       non_buffer();
    }

    // Set the variable $row to zero to begin counting entries
	$row = 0;

	// The ip-to-country.csv must be in the same directory as this php file
	$handle = fopen("ip-to-country.csv", "r");

	// Required to prevent timeout
	set_time_limit(300);

	// While rows exist, write each into the database
	while ($data = fgetcsv($handle, 1000, ",")) {
		$query = "INSERT INTO country_info(`IP_FROM`, `IP_TO`, `COUNTRY_CODE2`, `COUNTRY_CODE3`, `COUNTRY_NAME`)
        VALUES('".$data[0]."', '".$data[1]."', '".$data[2]."', '".$data[3]."', '". addslashes($data[4]) ."')";
		$result = mysql_query($query) or die("Invalid query: " . mysql_error().__LINE__.__FILE__);
		$row++;
	}

	// Close the database connection
	mysql_close($dbh);

    // Close the file handle
	fclose ($handle);

	// Print a confirmation
 echo "All done! " . $row . " rows added to database.";
    if ($C['non_buffer']) {
       non_buffer();
       ob_end_flush();
    }


function non_buffer() {
    ob_flush();
    //flush();
    usleep(700000);
}


?>